package com.qf.fmall2203.shopcart.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qf.fmall2203.shopcart.entity.ShoppingCart;
import com.qf.fmall2203.shopcart.service.IShoppingCartService;
import com.qf.fmall2203.utils.ResultVo;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 购物车  前端控制器
 * </p>
 *
 * @author dongjl
 * @since 2023-02-16
 */
@CrossOrigin
@RestController
@RequestMapping("/shopcart")
public class ShoppingCartController {

    @Autowired
    IShoppingCartService shoppingCartService;


    @GetMapping("/listbycids")
    public ResultVo listbycids(Integer[] cids){
        List<ShoppingCart> data = shoppingCartService.listbycids(cids);
        return ResultVo.ok(data);
    }


    @PutMapping("/update/{cartId}/{num}")
    public ResultVo update(@PathVariable("cartId") Integer cartId,@PathVariable("num") Integer num ){

        final boolean update = shoppingCartService.update(new UpdateWrapper<ShoppingCart>().set("cart_num", num).eq("cart_id", cartId));

        if (update){
            return ResultVo.ok();
        }else {
            return ResultVo.error();
        }

    }


    @GetMapping("/list")
    public ResultVo list(Integer userId){

        List<ShoppingCart> data = shoppingCartService.listShopcart(userId);

        return ResultVo.ok(data);

    }

    /**
     * 添加购物车
     */
    @PostMapping("/add")
    public ResultVo add(@RequestBody ShoppingCart shoppingCart){

        // 添加购物车日期
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String dateStr = simpleDateFormat.format(new Date());
        shoppingCart.setCartTime(dateStr);

        shoppingCartService.save(shoppingCart);

        return ResultVo.ok();

    }

}
